using System;
using System.Threading;

namespace Fadd.Commands
{
    /// <summary>
    /// Used to keep track of all asynchronous commands.
    /// </summary>
    internal class AsyncQueueItemResult : IAsyncResult
    {
        private bool _isCompleted;
        private readonly ManualResetEvent _asyncWaitHandle;
        private readonly object _asyncState;
        private readonly Command _command;
        private CommandEventArgs _args;

        public AsyncQueueItemResult(Command command, CommandEventArgs args,  object state)
        {
            _asyncWaitHandle = new ManualResetEvent(false);
            _asyncState = state;
            _command = command;
            _args = args;
        }

        internal void ToggleCompleted()
        {
            _isCompleted = true;
            _asyncWaitHandle.Set();
        }

        #region IAsyncResult Members

        ///<summary>
        ///Gets an indication whether the asynchronous operation has completed.
        ///</summary>
        ///
        ///<returns>
        ///true if the operation is complete; otherwise, false.
        ///</returns>
        ///<filterpriority>2</filterpriority>
        public bool IsCompleted
        {
            get { return _isCompleted; }
        }

        ///<summary>
        ///Gets a <see cref="T:System.Threading.WaitHandle"></see> that is used to wait for an asynchronous operation to complete.
        ///</summary>
        ///
        ///<returns>
        ///A <see cref="T:System.Threading.WaitHandle"></see> that is used to wait for an asynchronous operation to complete.
        ///</returns>
        ///<filterpriority>2</filterpriority>
        public WaitHandle AsyncWaitHandle
        {
            get { return _asyncWaitHandle; }
        }

        ///<summary>
        ///Gets a user-defined object that qualifies or contains information about an asynchronous operation.
        ///</summary>
        ///
        ///<returns>
        ///A user-defined object that qualifies or contains information about an asynchronous operation.
        ///</returns>
        ///<filterpriority>2</filterpriority>
        public object AsyncState
        {
            get { return _asyncState; }
        }

        ///<summary>
        ///Gets an indication of whether the asynchronous operation completed synchronously.
        ///</summary>
        ///
        ///<returns>
        ///true if the asynchronous operation completed synchronously; otherwise, false.
        ///</returns>
        ///<filterpriority>2</filterpriority>
        public bool CompletedSynchronously
        {
            get { return false; }
        }

        public Command Command
        {
            get { return _command; }
        }

        public CommandEventArgs Args
        {
            get { return _args; }
        }

        #endregion
    }

}
